package nancal.mp.db.mongo


import nancal.mp.db.mongo.table.*
import nbcp.base.utils.SpringUtil
import nbcp.myoql.db.db
import nbcp.myoql.db.mongo.MongoUpdateClip
import nbcp.myoql.db.mongo.base.MongoColumnName
import nbcp.myoql.db.mongo.component.MongoBaseMetaCollection
import org.slf4j.LoggerFactory
import org.springframework.data.mongodb.core.MongoTemplate
import java.io.Serializable

fun <M : MongoBaseMetaCollection<out E>, E : Any> MongoUpdateClip<M, E>.set(
    key: MongoColumnName,
    value: Any?
): MongoUpdateClip<M, E> {
    return this.set { key to value }
}

fun <M : MongoBaseMetaCollection<out E>, E : Any> MongoUpdateClip<M, E>.set(
    func: (M) -> MongoColumnName,
    value: Any?
): MongoUpdateClip<M, E> {
    return this.set { func(this.moerEntity) to value }
}

object mor {

    @JvmStatic
    val affectRowCount
        get() = db.affectRowCount


    @JvmStatic
    val shop
        get() = ShopGroup();

    @JvmStatic
    val log
        get() = LogGroup();


    @JvmStatic
    val finance
        get() = FinanceGroup();

    @JvmStatic
    val cms
        get() = CmsGroup();

    @JvmStatic
    val corp
        get() = CorpGroup();

    @JvmStatic
    val admin
        get() = AdminGroup()

    @JvmStatic
    val sys
        get() = SysGroup();

    @JvmStatic
    val wx
        get() = WxGroup();

    @JvmStatic
    val dev
        get() = DevGroup();

    @JvmStatic
    val yapi
        get() = YapiGroup();

    @JvmStatic
    val tenant
        get() = TenantGroup();

    @JvmStatic
    val base
        get() = db.morBase

    @JvmStatic
    val groups
        get() = db.mongo.groups

    fun getCollection(collectionName: String): MongoBaseMetaCollection<Serializable>? =
        db.mongo.mongoEvents.getCollection(collectionName);

    //        val event = SpringUtil.getBean<MongoEventConfig>()
    //
//        private val execAffectRows: ThreadLocal<Int> = ThreadLocal<Int>()
//
//        fun setMorExecAffectRows(n: Int) {
//            execAffectRows.set(n)
//        }
//
//        @JvmStatic
//        val affectRowCount: Int
//            get() {
//                return execAffectRows.get() ?: -1
//            }
//
//
//        @JvmStatic
//        val util = MongoUtil


    fun getMongoTemplate(planCode: Int = 0): MongoTemplate {
        var uri = SpringUtil.context.environment.getProperty("spring.data.mongodb.uri");
        if (planCode > 0) {
            uri = uri + "_" + planCode
        }
        var ret = db.mongo.getMongoTemplateByUri(uri)
        if (ret == null) {
            throw RuntimeException("获取动态数据库连接时出现异常")
        }
        return ret;
    }
}

